package com.eltsistemas.dao;

import com.eltsistema.hibernate.HibernateUtil;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import com.eltsistemas.modelo.Cliente;

public class ClienteDao {
	
    private Session session;
	
    public ClienteDao()
    {
	session = new HibernateUtil().getSession();
        session.beginTransaction();
    }
	
    public void adiciona(Cliente cliente)
    {
        session.save(cliente);
	session.getTransaction().commit();
        session.close();
    }
	
    public List<Cliente> lista()
    {
        List<Cliente> clienteList = session.createCriteria(Cliente.class).list();
        session.close();
	return clienteList;
    }
	
    public Cliente exibe(Cliente cliente)
    {
	Cliente encontradoCliente = (Cliente) session.load(Cliente.class, cliente.getId());
	return encontradoCliente;
    }
	
    public void altera(Cliente cliente)
    {
        session.update(cliente);
	session.getTransaction().commit();
        session.close();
    }
	
    public void remover(Cliente cliente)
    {
	session.delete(cliente);
	session.getTransaction().commit();
        session.close();
    }
	
    public Cliente buscaCodigo(Cliente cliente)
    {
	Query query = this.session.createQuery("from Cliente " +
                	"where razao = :razao or cnpj = :cnpj");
		
	query.setString("razao", cliente.getRazao());
        query.setString("cnpj", cliente.getCnpj());
				
	Cliente encontradaCliente = (Cliente) query.uniqueResult();
        session.close();
        return encontradaCliente;		
    }
    
    public Cliente buscaCodigoUp(Cliente cliente)
    {
	Query query = this.session.createQuery("from Cliente " +
                	"where (razao = :razao or cnpj = :cnpj) and (id != :id)");
		
	query.setString("razao", cliente.getRazao());
        query.setString("cnpj", cliente.getCnpj());
        query.setLong("id", cliente.getId());
				
	Cliente encontradaCliente = (Cliente) query.uniqueResult();
        session.close();
        return encontradaCliente;		
    }
    
     public Cliente buscaCodigo(String razao)
    {
	Query query = this.session.createQuery("from Cliente where razao =:razao");
                			
	query.setString("razao", razao);
       			
	Cliente encontradaCliente = (Cliente) query.uniqueResult();
        session.close();
        return encontradaCliente;	
    }

}
